package com.hb.game.pk.ui.activity.game;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.hb.game.pk.APP;
import com.hb.game.pk.R;
import com.hb.game.pk.adpter.ErBaChatAdapter;
import com.hb.game.pk.api.Host;
import com.hb.game.pk.api.RedBag;
import com.hb.game.pk.base.BaseActivity;
import com.hb.game.pk.beans.ErBaClickRedBean;
import com.hb.game.pk.beans.ErBaQzType1Bean;
import com.hb.game.pk.beans.ErBaQzType4Bean;
import com.hb.game.pk.beans.ErBaRoomStatus;
import com.hb.game.pk.beans.NullBean;
import com.hb.game.pk.beans.QzBean;
import com.hb.game.pk.beans.RoomList;
import com.hb.game.pk.event.MoneyChangeEvent;
import com.hb.game.pk.network.RetrofitCreateHelper;
import com.hb.game.pk.ui.activity.game.erba.ErBaRecordActivity;
import com.hb.game.pk.ui.activity.game.erba.ErBaXZActivity;
import com.hb.game.pk.ui.activity.game.erba.OpenRedActivity;
import com.hb.game.pk.utils.LogUtils;
import com.hb.game.pk.utils.SocketUtils;
import com.hb.game.pk.utils.StringUtils;
import com.hb.game.pk.utils.ToastUtils;
import com.hb.game.pk.widgets.titlebar.TitleBar;


import org.greenrobot.eventbus.EventBus;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ErBaChatActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.tv_next_z_money)
    TextView tvNextZMoney;
    @BindView(R.id.tv_line_moeny)
    TextView tvLineMoeny;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_qz)
    TextView tvQz;
    @BindView(R.id.tv_z_name)
    TextView tvZName;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.rl_box)
    LinearLayout rlBox;
    @BindView(R.id.ll_kjjl)
    LinearLayout llKjjl;
    @BindView(R.id.ll_xzjl)
    LinearLayout llXzjl;
    @BindView(R.id.ll_zjjl)
    LinearLayout llZjjl;
    @BindView(R.id.rl_more)
    RelativeLayout rlMore;
    @BindView(R.id.rl_dialog)
    RelativeLayout rlDialog;
    @BindView(R.id.rv_list)
    ListView rv_list;
    @BindView(R.id.wv_web)
    WebView wvWeb;
    private RoomList.DataBean dataBean;
    private MaterialDialog moneyDialog;
    List<Map> data = new ArrayList<>();
    private ErBaChatAdapter myAdapter;
    private MaterialDialog qzDialog;
    private QzBean.DataBean qzData;
    SocketUtils socketUtils;
    WebSocketClient open;
    private Gson gson = new Gson();
    String chang_id;
    String lineQzMoney;
    private String clickHbId;
    private Call<ErBaClickRedBean> clickCall;
    private ErBaClickRedBean.DataBean clickData;
    private Call<NullBean> openResult;
    private boolean canQz = false;
    private boolean canXZ = false;
    private MaterialDialog redDialog;
    private String moneyLine;
    private String zj_id;
    private CountDownTimer timer;
    private int count_time;
    private Call<NullBean> getpeople;
    private Call<ErBaRoomStatus> statusCall;
    private Call<QzBean> qzCall;
    private Call<NullBean> getmoney;
    boolean isFirstQz = false;
    boolean isFirstXz = false;
    private Thread countThread;
    private int fakeTime = 20;
    private int fakeCountTime = 0;
    private boolean fakeTag = true;
    private Call<NullBean> xzCall;
    private String re_moneyLine;
    private Thread countOtherThread;
    private boolean fakeOtherTag = true;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat_erba;
    }

    @Override
    protected int getRootViewId() {
        return R.id.layout_root;
    }

    @Override
    protected int getRefreshId() {
        return 0;
    }

    @Override
    protected int getListViewId() {
        return 0;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Intent intent = getIntent();
        String room = intent.getStringExtra("room");
        dataBean = new Gson().fromJson(room, RoomList.DataBean.class);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.getLlLeft().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ErBaChatActivity.this.finish();
            }
        });
        titleBar.setTitle(dataBean.getTitle());
        tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), "0")));
        tvLineMoeny.setText("0");
        tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), 0)));
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        getpeople = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getpeople();
        getpeople.enqueue(new Callback<NullBean>() {
            @Override
            public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                NullBean body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                if (body.getData() != null)
                    titleBar.setRightText(body.getData().toString());
            }

            @Override
            public void onFailure(Call<NullBean> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });

        statusCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).erba_get_status(dataBean.getRoom_id());
        statusCall.enqueue(new Callback<ErBaRoomStatus>() {
            @Override
            public void onResponse(Call<ErBaRoomStatus> call, Response<ErBaRoomStatus> response) {
                ErBaRoomStatus body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                ErBaRoomStatus.DataBean data = body.getData();
                zj_id = data.getUser_id();
                re_moneyLine=Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
                if (data.getStatus() == 1) {
                    canQz = true;
                    if (data.getStart_time() != 0) {
                        count_time = data.getStart_time();
                        moneyLine = Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
                        //re_moneyLine = moneyLine;
                        lineQzMoney = Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
                        tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), moneyLine)));
                        tvLineMoeny.setText(String.format(String.format(getResources().getString(R.string.erba_line_money), moneyLine)));
                        tvQz.setText("抢庄");
                        if (count_time != -1) {
                            getTime(count_time, true, false, false);
                        } else {
                            initThread(false);
                        }
                    }
                } else if (data.getStatus() == 2) {
                    canQz = false;
                    canXZ = true;
                    initStatus(data, 2);
                } else if (data.getStatus() == 3) {
                    canQz = false;
                    canXZ = false;
                    initStatus(data, 3);
                } else if (data.getStatus() == 4) {
                    count_time = data.getStart_time();
                    moneyLine = Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
                    lineQzMoney = Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
                    tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), moneyLine)));
                }
            }

            @Override
            public void onFailure(Call<ErBaRoomStatus> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
        initMyAdapter();

        Map<String, String> jsonMap = new HashMap<>();
        jsonMap.put("roomid", dataBean.getRoom_id());
        jsonMap.put("uid", APP.uid);
        jsonMap.put("m", "index");
        jsonMap.put("a", "slogin");
        String socketJson = new Gson().toJson(jsonMap);
        try {
            doConn(socketJson);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            ToastUtils.showToast("socket错误");
        }
    }

    private void initStatus(ErBaRoomStatus.DataBean data, int status) {
        moneyLine = Float.parseFloat(data.getShangzhuang_money()) / 100 + "";
        lineQzMoney = moneyLine;
        tvLineMoeny.setText(Float.parseFloat(data.getMoney()) / 100 + "");
        tvZName.setText(data.getNickname());
        chang_id = data.getChang_id();
        tvNextZMoney.setText(String.format(getResources().getString(R.string.erba_next_z_money), Float.parseFloat(data.getMoney()) / 100 + ""));
        count_time = data.getStart_time();
        if (status == 2) {
            tvQz.setText("下注");
        } else {
            tvQz.setText("抢庄");
        }
        if (count_time > 0) {
            if (status == 2) {
                ToastUtils.showToast("当前局正在进行中，请下注");
                getTime(count_time, false, true, false);
            } else {
                getTime(count_time, false, false, true);
            }
        } else {
            ToastUtils.showToast("当前局正在进行中，请等待下一局");
        }
    }

    Map addMap;

    private void doConn(final String text) throws URISyntaxException {
        if (socketUtils == null) {
            socketUtils = new SocketUtils(Host.SOCKETHOST, text);
            socketUtils.setOnOpenListener(new SocketUtils.OnOpenListener() {
                @Override
                public void setOnOpenListener(ServerHandshake handshakedata) {
                    socketUtils.setText(text);
                }
            });
            socketUtils.setOnCloseListener(new SocketUtils.OnCloseListener() {
                @Override
                public void setOnCloseListener(int code, String reason, boolean remote) {
                }
            });
            socketUtils.setOnErrorListener(new SocketUtils.OnErrorListener() {
                @Override
                public void setOnErrorListener(Exception ex) {
                    LogUtils.d("OnErrorListener");
                    ex.printStackTrace();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (open != null) {
                                open.reconnect();
                            }
                        }
                    }.start();
                }
            });
            socketUtils.setOnMessageListener(new SocketUtils.OnMessageListener() {
                @Override
                public void setOnMessageListener(String message) {
                    if (message.contains("logout"))
                        return;
                    if (message.contains("slogin"))
                        return;
                    addMap = new Gson().fromJson(message, Map.class);
                    if (addMap.get("roomid") == null || Double.parseDouble(dataBean.getRoom_id()) != Double.parseDouble(addMap.get("roomid").toString()))
                        return;
                    LogUtils.d("message___  " + message);
                    if (addMap.containsKey("m")) {
                        if (addMap.containsKey("type")) {
                            if (Double.parseDouble(addMap.get("type").toString()) == 1.0) {
                                String s = gson.toJson(addMap);
                                ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                if (!isFirstQz) {
                                    ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvQz.setText("抢庄");
                                            tvLineMoeny.setText(String.format(String.format(getResources().getString(R.string.erba_line_money), moneyLine)));
                                            if (tvQz.getVisibility() != View.VISIBLE) {
                                                tvQz.setVisibility(View.VISIBLE);
                                            }
                                        }
                                    });
                                    fakeTag = false;
                                    fakeOtherTag = false;
                                    isFirstQz = true;
                                    getTime(erBaQzBean.getData().getStart_time(), true, false, false);
                                }
                            }
                            if (Double.parseDouble(addMap.get("type").toString()) == 2.0) {
                                ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String s = gson.toJson(addMap);
                                        ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                        tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), (Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f) + "")));
                                        tvLineMoeny.setText(Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f + "");
                                        tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), 0)));
                                        moneyLine = Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f + "";
                                        tvZName.setText(erBaQzBean.getData().getUsername());
                                        chang_id = erBaQzBean.getData().getChang_id();
                                        lineQzMoney = (Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f) + "";
                                        zj_id = erBaQzBean.getData().getUser_id();
                                        canQz = false;
                                        canXZ = true;
                                        fakeTag = false;
                                        fakeOtherTag = false;
                                        if (tvQz.getVisibility() != View.VISIBLE) {
                                            tvQz.setVisibility(View.VISIBLE);
                                        }
                                        if (tvQz.getVisibility() != View.VISIBLE) {
                                            tvQz.setVisibility(View.VISIBLE);
                                        }
                                        if (!isFirstXz) {
                                            tvQz.setText("下注");
                                            isFirstXz = true;
                                            isFirstQz = false;
                                            getTime(erBaQzBean.getData().getStart_time(), false, true, false);
                                        }
                                    }
                                });
                            }
                            if (Double.parseDouble(addMap.get("type").toString()) == 4.0) {
                                canXZ = false;
                                isFirstXz = false;
                                String s = gson.toJson(addMap);
                                ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                fakeTag = false;
                                fakeOtherTag = false;
                                getTime(erBaQzBean.getData().getStart_time(), false, false, true);
                            }
                            if (Double.parseDouble(addMap.get("type").toString()) == 5.0) {
                                ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvQz.setText("抢庄");
                                        tvZName.setText("用户昵称");
                                        tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), 0)));
                                        tvLineMoeny.setText("0");
                                    }
                                });
                                count_time = -1;
                                canQz = true;
                                isFirstQz = false;
                                isFirstXz = false;
                                String s = gson.toJson(addMap);
                                ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                chang_id = erBaQzBean.getData().getChang_id();
                                fakeTag = true;
                                fakeOtherTag = false;
                                initThread(false);
                            }
                            if (Double.parseDouble(addMap.get("type").toString()) == 6.0) {
                                ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvQz.setText("下注");
                                        String s = gson.toJson(addMap);
                                        ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                        if (tvQz.getVisibility() != View.VISIBLE) {
                                            tvQz.setVisibility(View.VISIBLE);
                                        }
                                        tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), (Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f) + "")));
                                        tvLineMoeny.setText(Float.parseFloat(erBaQzBean.getData().getMoney()) / 100f + "");
                                    }
                                });
                                String s = gson.toJson(addMap);
                                ErBaQzType1Bean erBaQzBean = gson.fromJson(s, ErBaQzType1Bean.class);
                                chang_id = erBaQzBean.getData().getChang_id();
                                zj_id = erBaQzBean.getData().getUser_id();
                                canQz = false;
                                canXZ = true;
                                fakeTag = false;
                                fakeOtherTag = false;
                                if (!isFirstXz) {
                                    isFirstXz = true;
                                    isFirstQz = false;
                                    getTime(erBaQzBean.getData().getStart_time(), false, true, false);
                                }
                            }
                            if (Double.parseDouble(addMap.get("type").toString()) == 7.0) {
                                canQz = true;
                                canXZ = false;
                                count_time = -1;
                                ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvZName.setText("用户昵称");
                                        tvQz.setText("抢庄");
                                        tvLineMoeny.setText("0");
                                        tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), 0)));
                                        moneyLine = re_moneyLine;
                                        tvLineMoeny.setText(String.format(String.format(getResources().getString(R.string.erba_line_money), moneyLine)));
                                        tvNextZMoney.setText(String.format(String.format(getResources().getString(R.string.erba_next_z_money), moneyLine)));
                                    }
                                });
                                if (timer != null) {
                                    timer.cancel();
                                }
                                fakeTag = false;
                                fakeOtherTag = true;
                                initOtherThread();
                                return;
                            }
                        } else {
                            canQz = true;
                            canXZ = false;
                            count_time = -1;
                            ErBaChatActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!ErBaChatActivity.this.isFinishing()) {
                                        tvLineMoeny.setText(String.format(String.format(getResources().getString(R.string.erba_line_money), moneyLine)));
                                        if (!StringUtils.isEmpty(zj_id) && zj_id.equals(APP.uid))
                                            tvQz.setText("下庄");
                                        else {
                                            tvQz.setVisibility(View.INVISIBLE);
                                            tvQz.setText("抢庄");
                                        }
                                    }
                                }
                            });
                            if (timer != null) {
                                timer.cancel();
                            }
                            fakeTag = true;
                            fakeOtherTag = false;
                            initThread(true);
                        }
                    }
                    if (myAdapter != null) {
                        rv_list.post(new Runnable() {
                            @Override
                            public void run() {
                                myAdapter.addMore(addMap);
                                rv_list.setSelection(myAdapter.getData().size() - 1);
                            }
                        });
                    }
                }
            });
        }
        if (open == null) {
            open = socketUtils.open();
        }
        open.connect();

    }

    protected void initMyAdapter() {
        if (myAdapter == null) {
            myAdapter = new ErBaChatAdapter(this, rv_list);
            myAdapter.setNewData(data);
            rv_list.setAdapter(myAdapter);
            rv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    List<Map> data = myAdapter.getData();
                    Map map = data.get(position);
                    if (map.containsKey("m")) {
                        LogUtils.d("map___  " + map);
                        if (map.containsKey("type")) {
                            if (Double.parseDouble(map.get("type").toString()) == 4.0) {
                                String s = gson.toJson(map);
                                ErBaQzType4Bean erBaQzType4Bean = gson.fromJson(s, ErBaQzType4Bean.class);
                                ErBaQzType4Bean.DataBean clickData = erBaQzType4Bean.getData();
                                clickHbId = clickData.getHongbao_id();
                                rv_list.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        myAdapter.setStatus(position);
                                    }
                                });
                                showClickBagDialog(myAdapter, position);
                            }
                        }
                    }
                }
            });
            if (rv_list.getCount() != 0)
                rv_list.setSelection(rv_list.getCount() - 1);
        } else {
            myAdapter.setNewData(data);
            if (rv_list.getCount() != 0)
                rv_list.setSelection(rv_list.getCount() - 1);
        }
    }

    private void showClickBagDialog(final ErBaChatAdapter myAdapter, final int position) {
        clickCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).erba_click_hb(clickHbId, chang_id);
        clickCall.enqueue(new Callback<ErBaClickRedBean>() {
            @Override
            public void onResponse(Call<ErBaClickRedBean> call, Response<ErBaClickRedBean> response) {
                ErBaClickRedBean body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                clickData = body.getData();

                if (redDialog == null) {
                    View inflate = View.inflate(ErBaChatActivity.this, R.layout.dialog_red_open, null);
                    ImageView ivOpen = (ImageView) inflate.findViewById(R.id.iv_open);
                    TextView tvDetail = (TextView) inflate.findViewById(R.id.tv_detail);
                    tvDetail.setVisibility(View.GONE);
                    ImageView ivClose = (ImageView) inflate.findViewById(R.id.iv_close);
                    tvDetail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.putExtra("clickHbId", clickHbId);
                            redDialog.dismiss();
                            startActivity(OpenRedActivity.class, intent);
                        }
                    });
                    ivOpen.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openResult = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).erba_get_hongbao(dataBean.getRoom_id(), clickData.getId(), clickData.getChang_id());
                            openResult.enqueue(new Callback<NullBean>() {
                                @Override
                                public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                                    NullBean body = response.body();
                                    if (body == null) {
                                        ToastUtils.showToast("请求错误");
                                        return;
                                    }
                                    if (body.getStatus() != 1) {
                                        ToastUtils.showToast(body.getInfo());
                                        return;
                                    }
                                    redDialog.dismiss();
                                    Intent intent = new Intent();
                                    intent.putExtra("clickHbId", clickHbId);
                                    redDialog.dismiss();
                                    startActivity(OpenRedActivity.class, intent);
                                }

                                @Override
                                public void onFailure(Call<NullBean> call, Throwable t) {
                                    ToastUtils.showToast("网络请求错误");
                                }
                            });
                        }
                    });
                    redDialog = new MaterialDialog.Builder(ErBaChatActivity.this)
                            .customView(inflate, false).show();
                    ivClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            redDialog.dismiss();
                        }
                    });
                } else {
                    if (redDialog.isShowing()) {
                        redDialog.dismiss();
                    } else {
                        redDialog.show();
                    }
                }

                View customView = redDialog.getCustomView();
                ImageView ivOpen = (ImageView) customView.findViewById(R.id.iv_open);
                TextView tvTS = (TextView) customView.findViewById(R.id.tv_ts);
                TextView tvName = (TextView) customView.findViewById(R.id.tv_name);
                TextView tvDetail = (TextView) customView.findViewById(R.id.tv_detail);
                tvDetail.setVisibility(View.GONE);
                tvTS.setVisibility(View.GONE);
                tvName.setText(clickData.getUsername());
                if (clickData.getType() == 1) {
                    // 领取
                    ivOpen.setVisibility(View.VISIBLE);
                    tvDetail.setVisibility(View.VISIBLE);
                } else {
                    ivOpen.setVisibility(View.GONE);
                    // 领完
                    tvTS.setText(clickData.getRemark());
                    tvTS.setVisibility(View.VISIBLE);
                    tvDetail.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFailure(Call<ErBaClickRedBean> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
    }

    @OnClick({R.id.tv_start, R.id.iv_add, R.id.ll_kjjl, R.id.ll_xzjl, R.id.ll_zjjl, R.id.tv_qz, R.id.tv_money, R.id.rl_dialog})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.tv_start:
                if (APP.uid.equals(zj_id)) {
                    ToastUtils.showToast("庄家不能下注");
                    return;
                }
                if (canXZ) {
                    if (count_time > 0) {
                        intent.putExtra("time", count_time);
                        intent.putExtra("chang_id", chang_id);
                        intent.putExtra("room_id", dataBean.getRoom_id());
                        startActivity(ErBaXZActivity.class, intent);
                    } else {
                        ToastUtils.showToast("下注时间已过，请等待下一局");
                    }
                } else {
                    ToastUtils.showToast("当前正有在一局进行,请等待下一局");
                }
                break;
            case R.id.iv_add:
                resetListViewHeight();
                break;
            case R.id.ll_kjjl:
                if (rlDialog.getVisibility() == View.VISIBLE) {
                    rlDialog.setVisibility(View.GONE);
                } else {
                    rlDialog.setVisibility(View.VISIBLE);
                    getKJJL();
                }
                break;
            case R.id.ll_xzjl:
                intent.putExtra("type", 1);
                startActivity(ErBaRecordActivity.class, intent);
                break;
            case R.id.ll_zjjl:
                intent.putExtra("type", 2);
                startActivity(ErBaRecordActivity.class, intent);
                break;
            case R.id.tv_qz:
                String s = tvQz.getText().toString();
                if ("抢庄".equals(s) || "无庄".equals(s)) {
                    if (canQz) {
                        if (count_time > 0 || count_time == -1) {
                            showQzDialog();
                        } else {
                            ToastUtils.showToast("抢庄时间已过，请等待下一局");
                        }
                    } else {
                        ToastUtils.showToast("当前正有在一局进行");
                    }
                }
                if ("下庄".equals(s)) {
                    fakeTag = false;
                    xiaZhuang();
                }
                if ("下注".equals(s)) {
                    if (APP.uid.equals(zj_id)) {
                        ToastUtils.showToast("庄家不能下注");
                        return;
                    }
                    if (canXZ) {
                        if (count_time > 0) {
                            intent.putExtra("time", count_time);
                            intent.putExtra("chang_id", chang_id);
                            intent.putExtra("room_id", dataBean.getRoom_id());
                            startActivity(ErBaXZActivity.class, intent);
                        } else {
                            ToastUtils.showToast("当前不可下注");
                        }
                    } else {
                        ToastUtils.showToast("当前不可下注");
                    }
                }
                break;
            case R.id.tv_money:
                getMineMoney();
                break;
            case R.id.rl_dialog:
                rlDialog.setVisibility(View.GONE);
                break;
        }
    }

    private void xiaZhuang() {
        xzCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).erba_xiazhuang(dataBean.getRoom_id());
        xzCall.enqueue(new Callback<NullBean>() {
            @Override
            public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                NullBean body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                }
                ToastUtils.showToast(body.getInfo());
                tvQz.setText("抢庄");
            }

            @Override
            public void onFailure(Call<NullBean> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
    }

    private void showQzDialog() {
        if (qzDialog == null) {
            View inflate = View.inflate(this, R.layout.dialog_erba_qz_dialog, null);
            TextView tvMoneyLine = (TextView) inflate.findViewById(R.id.tv_money_line);
            TextView tvCansle = (TextView) inflate.findViewById(R.id.tv_cansle);
            TextView tvOk = (TextView) inflate.findViewById(R.id.tv_ok);
            tvMoneyLine.setText(String.format(getResources().getString(R.string.dialog_erba_qz), moneyLine));
            final EditText etMoneyQz = (EditText) inflate.findViewById(R.id.et_money_qz);
            tvOk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = etMoneyQz.getText().toString();
                    etMoneyQz.setText("");
                    if (StringUtils.isEmpty(s)) {
                        ToastUtils.showToast("请输入金额");
                        return;
                    }
                    if (Float.parseFloat(s) < Float.parseFloat(moneyLine)) {
                        ToastUtils.showToast("金额必须大于" + Float.parseFloat(moneyLine));
                        return;
                    }
                    if (qzDialog.isShowing()) {
                        qzDialog.dismiss();
                    }
                    qzCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).erba_rob(dataBean.getRoom_id(), s);
                    qzCall.enqueue(new Callback<QzBean>() {
                        @Override
                        public void onResponse(Call<QzBean> call, Response<QzBean> response) {
                            QzBean body = response.body();
                            if (body == null) {
                                ToastUtils.showToast("请求错误");
                                return;
                            }
                            if (body.getStatus() != 1) {
                                ToastUtils.showToast(body.getInfo());
                                return;
                            }
                            qzData = body.getData();
                        }

                        @Override
                        public void onFailure(Call<QzBean> call, Throwable t) {
                            ToastUtils.showToast("网络请求错误");
                        }
                    });
                }
            });
            tvCansle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etMoneyQz.setText("");
                    if (qzDialog.isShowing()) {
                        qzDialog.dismiss();
                    }
                }
            });
            qzDialog = new MaterialDialog.Builder(ErBaChatActivity.this)
                    .customView(inflate, false).show();
        } else {
            View customView = qzDialog.getCustomView();
            TextView tvMoneyLine = (TextView) customView.findViewById(R.id.tv_money_line);
            tvMoneyLine.setText(String.format(getResources().getString(R.string.dialog_erba_qz), moneyLine));
            if (qzDialog.isShowing()) {
                qzDialog.dismiss();
            } else {
                qzDialog.show();
            }
        }
    }

    private void resetListViewHeight() {
        int height = 0;
        if (rlMore.getVisibility() == View.VISIBLE) {
            rlMore.setVisibility(View.GONE);
            height = getResources().getDimensionPixelOffset(R.dimen.px100);
        } else {
            rlMore.setVisibility(View.VISIBLE);
            height = getResources().getDimensionPixelOffset(R.dimen.px300);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        params.setMargins(0, 0, 0, height);
        params.addRule(RelativeLayout.BELOW, R.id.rl_start);
        rv_list.setLayoutParams(params);
    }

    private void getKJJL() {
        WebSettings webSetting = wvWeb.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        webSetting.setSupportZoom(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setLoadWithOverviewMode(true);
        WebChromeClient client = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        };
        wvWeb.setWebChromeClient(client);
//            Map<String, String> map = new HashMap<String, String>();
//            map.put("token", APP.Token);
//            map.put("userid", APP.uid);
//            webView.loadUrl("https://www.baidu.com", map);
        wvWeb.loadUrl("http://game1gao.weiquer.com/jilu/kaijiang.html");
        wvWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });
    }

    private void getMineMoney() {
        getmoney = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getmoney();
        getmoney.enqueue(new Callback<NullBean>() {
            @Override
            public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                NullBean body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                if (moneyDialog == null) {
                    View inflate = View.inflate(ErBaChatActivity.this, R.layout.dialog_money_view, null);
                    Button btnClose = (Button) inflate.findViewById(R.id.btn_close);
                    TextView tvMoney = (TextView) inflate.findViewById(R.id.tv_money);
                    tvMoney.setText("0");
                    if (body.getData() != null)
                        tvMoney.setText(String.format(getResources().getString(R.string.mine_money), (Float.parseFloat(body.getData().toString()) / 100f) + ""));
                    moneyDialog = new MaterialDialog.Builder(ErBaChatActivity.this)
                            .customView(inflate, false).show();
                    btnClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (moneyDialog != null && moneyDialog.isShowing()) {
                                moneyDialog.dismiss();
                            }
                        }
                    });
                } else {
                    if (moneyDialog.isShowing()) {
                        moneyDialog.dismiss();
                    } else {
                        View customView = moneyDialog.getCustomView();
                        TextView tvMoney = (TextView) customView.findViewById(R.id.tv_money);
                        tvMoney.setText("0");
                        if (body.getData() != null)
                            tvMoney.setText(String.format(getResources().getString(R.string.mine_money), (Float.parseFloat(body.getData().toString()) / 100f) + ""));
                        moneyDialog.show();
                    }
                }
            }

            @Override
            public void onFailure(Call<NullBean> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (open != null) {
            open.close();
        }
        if (redDialog != null) {
            if (redDialog.isShowing()) {
                redDialog.dismiss();
            }
        }
        if (qzDialog != null) {
            if (qzDialog.isShowing()) {
                qzDialog.dismiss();
            }
        }
        if (openResult != null) {
            openResult.cancel();
        }
        if (clickCall != null) {
            clickCall.cancel();
        }
        if (getpeople != null) {
            getpeople.cancel();
        }
        if (statusCall != null) {
            statusCall.cancel();
        }
        if (qzCall != null) {
            qzCall.cancel();
        }
        if (xzCall != null) {
            xzCall.cancel();
        }
        if (getmoney != null) {
            getmoney.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
        fakeTag = false;
        EventBus.getDefault().post(new MoneyChangeEvent());
    }

    private void getTime(final int time, final boolean isQz, final boolean isXz, final boolean isQb) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timer = new CountDownTimer(time * 1000, 1000) {
                    @Override
                    public void onTick(long l) {
                        count_time = Integer.parseInt(l / 1000 + "");
                        int string_id = 0;
                        if (isQz) {
                            string_id = R.string.erba_start_time;
                        } else if (isXz) {
                            string_id = R.string.erba_xz_start_time;
                        } else if (isQb) {
                            string_id = R.string.erba_qb_start_time;
                        }
                        tvStartTime.setText(String.format(String.format(getResources().getString(string_id), count_time)));
                    }

                    @Override
                    public void onFinish() {
                        int string_id = 0;
                        if (isQz) {
                            string_id = R.string.erba_start_time;
                        } else if (isXz) {
                            string_id = R.string.erba_xz_start_time;
                        } else if (isQb) {
                            string_id = R.string.erba_qb_start_time;
                        }
                        tvStartTime.setText(String.format(String.format(getResources().getString(string_id), 0)));
                    }
                };
                timer.start();
            }
        });
    }

    private void initThread(final boolean tag) {
        if (tag) {
            fakeTime = 5;
        } else {
            fakeTime = 20;
        }
        countThread = new Thread() {
            @Override
            public void run() {
                super.run();
                while (fakeTag) {
                    for (int i = fakeTime; i >= 0 && fakeTag; i--) {
                        fakeCountTime = i;
                        ErBaChatActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!ErBaChatActivity.this.isFinishing()) {
                                    tvStartTime.setText("");
                                    tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), fakeCountTime)));
                                    if (tag && fakeCountTime == 0) {
                                        if (APP.uid.equals(zj_id)) {
                                            tvQz.setVisibility(View.GONE);
                                        }
                                        fakeTag = false;
                                    }
                                }
                            }
                        });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        countThread.start();
    }

    private void initOtherThread() {
        fakeTime = 20;
        countOtherThread = new Thread() {
            @Override
            public void run() {
                super.run();
                while (fakeOtherTag) {
                    for (int i = fakeTime; i > 0 && fakeOtherTag; i--) {
                        fakeCountTime = i;
                        ErBaChatActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!ErBaChatActivity.this.isFinishing()) {
                                    tvStartTime.setText("");
                                    tvStartTime.setText(String.format(String.format(getResources().getString(R.string.erba_start_time), fakeCountTime)));
                                    if (tvQz.getVisibility() != View.VISIBLE)
                                        tvQz.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (i == 0) {
                            fakeOtherTag = false;
                        }
                    }
                }
            }
        };
        countOtherThread.start();
    }
}
